package com.asset.dispoal.file.evidenceRecognition;

import com.asset.dispoal.business.common.KeyValue;
import com.asset.dispoal.file.evidenceRecognition.api.EvidenceRecognitionService;
import com.asset.dispoal.file.evidenceRecognition.dto.CaseEvidenceRecognitionRequest;
import com.asset.dispoal.file.evidenceRecognition.dto.DownloadAndDelEvidenceRequest;
import com.asset.dispoal.file.evidenceRecognition.dto.EvidenceRecognitionProRequest;
import com.asset.dispoal.file.evidenceRecognition.dto.EvidenceRecognitionRequest;
import com.asset.dispoal.file.evidenceRecognition.dto.FileByZipRequest;
import com.asset.dispoal.file.evidenceRecognition.dto.ManyDownloadDetailRequest;
import com.asset.dispoal.file.evidenceRecognition.dto.ManyDownloadRequest;
import com.asset.dispoal.file.evidenceRecognition.dto.MergeEvidenceDownloadRequest;
import com.asset.dispoal.file.evidenceRecognition.dto.SingleEvidenceRecognitionRequest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import tech.mhuang.pacebox.core.compress.DynamicRenameFile;
import tech.mhuang.pacebox.core.file.FileUtil;
import tech.mhuang.pacebox.core.util.ZipUtil;
import tech.mhuang.pacebox.springboot.protocol.Result;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author qr
 * @date 2022/4/14$
 */
@RestController
@Api(value = "证据管理", tags = "证据管理")
@RequestMapping("file/evidenceRecognition")
public class EvidenceRecognitionController {

    @Autowired
    EvidenceRecognitionService evidenceRecognitionService;

    @Autowired
    private Environment environment;

    @ApiOperation(value = "单个证据上传", notes = "单个证据上传")
    @PostMapping(value = "singleEvidenceUpload")
    public Result singleEvidenceUpload(SingleEvidenceRecognitionRequest request) {
        return evidenceRecognitionService.singleEvidenceUpload(request);
    }

    @ApiOperation(value = "单个合同的种类证据下载、成功获取对应地址")
    @PostMapping("downloadEvidenceFileByZip")
    public Result<String> downloadEvidenceFileByZip(@RequestBody FileByZipRequest request) {
        return evidenceRecognitionService.downloadFileByZip(request);
    }

    @ApiOperation(value = "下载并删除未匹配到的证据")
    @PostMapping("downloadAndDelEvidence")
    public Result<String> downloadAndDelEvidence(@RequestBody DownloadAndDelEvidenceRequest request) {
        return evidenceRecognitionService.downloadAndDelEvidence(request);
    }

    @ApiOperation("证据打包下载")
    @PostMapping("downloadMergeEvidence")
    public Result downloadMergeEvidence(MergeEvidenceDownloadRequest request) {
        return evidenceRecognitionService.downloadMergeEvidence(request);
    }

    @ApiOperation(value = "单个合同证据种类下载完")
    @GetMapping("downloadEvidenceFile")
    public ResponseEntity<byte[]> downloadEvidenceFile(String fileUrl) {
        String evidenceUrl = environment.getProperty("file.evidence.url");
        File file = new File(evidenceUrl + fileUrl);
        return commonDownload(file);
    }

    @ApiOperation(value = "单个合同证据种类下载完")
    @GetMapping("downloadNasFile")
    public ResponseEntity<byte[]> downloadNasFile(String fileUrl) {
        String nasFileUrl = environment.getProperty("file.nasFile.url");
        File file = new File(nasFileUrl + fileUrl);
        return commonDownload(file);
    }

    @ApiOperation(value = "多个合同证据种类下载完")
    @GetMapping("downloadEvidenceFileList")
    public ResponseEntity<byte[]> downloadEvidenceFileList(ManyDownloadRequest request) {
        DynamicRenameFile zipDynamicRenameFileDTO = new DynamicRenameFile();
        zipDynamicRenameFileDTO.setDirName(request.getDirName());
        for (ManyDownloadDetailRequest detailRequest : request.getDownloadFileList()) {
            zipDynamicRenameFileDTO.addRenameFile(detailRequest.getSourceName(), new File(environment.getProperty("file.evidence.url") + detailRequest.getFileUrl()));
        }

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipUtil.toDynamicRenameZip(Collections.singletonList(zipDynamicRenameFileDTO), outputStream);
        return commonDownload(outputStream, request.getDownloadName());
    }

    private ResponseEntity<byte[]> commonDownload(ByteArrayOutputStream outputStream, String downloadName) {
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentDispositionFormData("attachment", new String(downloadName.getBytes(), "iso-8859-1"));
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            return new ResponseEntity<>(outputStream.toByteArray(), headers, HttpStatus.CREATED);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    private ResponseEntity<byte[]> commonDownload(File file) {
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentDispositionFormData("attachment", new String(file.getName().getBytes(), "iso-8859-1"));
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            return new ResponseEntity<>(FileUtil.readFileToByteArray(file), headers, HttpStatus.CREATED);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    @ApiOperation(value = "下载")
    @GetMapping("/downloadFile")
    public ResponseEntity<byte[]> downloadFile(@RequestParam("name") String name, @RequestParam("type") String type, @RequestParam("location") String location) {
        File file = new File(String.format("%s%s.%s", environment.getProperty("file." + location + ".url"), name, type));
        return commonDownload(file);
    }

    @ApiOperation(value = "证据上传", notes = "证据上传")
    @PostMapping(value = "/evidenceUpload")
    public Result evidenceUpload(@ApiParam("总片数") @RequestParam(name = "dzTotalChunkCount", required = false) String chunks,
                                 @ApiParam("当前片索引") @RequestParam(name = "dzChunkIndex", required = false) String chunk,
                                 @RequestParam(name = "dzUuid", required = false) String taskId,
                                 @RequestParam(name = "dzFilename", required = false) String name,
                                 @RequestParam(name = "fileName", required = false) String filename,
                                 @ModelAttribute EvidenceRecognitionRequest evidenceRecognitionRequest,
                                 @RequestParam("file") MultipartFile file, @RequestParam("uid") String uuid,
                                 @RequestParam(name = "state", required = false) String state) {
        return evidenceRecognitionService.evidenceUpload(chunks, chunk, taskId, name, evidenceRecognitionRequest, file, state, filename, uuid);
    }

    @ApiOperation(value = "证据上传Pro", notes = "证据上传Pro")
    @PostMapping(value = "/evidenceUploadPro")
    public Result evidenceUploadPro(@ApiParam("总片数") @RequestParam(name = "dzTotalChunkCount", required = false) String chunks,
                                    @ApiParam("当前片索引") @RequestParam(name = "dzChunkIndex", required = false) String chunk,
                                    @RequestParam(name = "dzUuid", required = false) String taskId,
                                    @RequestParam(name = "dzFilename", required = false) String name,
                                    @RequestParam(name = "fileName", required = false) String filename,
                                    @ModelAttribute EvidenceRecognitionProRequest evidenceRecognitionRequest,
                                    @RequestParam("file") MultipartFile file,
                                    @RequestParam("uid") String uuid,
                                    @RequestParam(name = "no", required = false) String no,
                                    @RequestParam(name = "state", required = false) String state) {

        return evidenceRecognitionService.evidenceUploadPro(chunks, chunk, taskId, name, evidenceRecognitionRequest, file, no, state, filename, uuid);
    }

    @ApiOperation(value = "案件证据上传", notes = "案件证据上传")
    @PostMapping(value = "/caseEvidenceUpload")
    public Result caseEvidenceUpload(CaseEvidenceRecognitionRequest request) {
        return evidenceRecognitionService.caseEvidenceUpload(request);
    }

    @GetMapping("/queryActionKey")
    @ApiOperation(value = "查询上传通知书的识别关键字", notes = "查询上传通知书的识别关键字")
    public Result<List<KeyValue<String, String>>> queryActionKey() {
        return Result.ok(Stream.of(KeyValue.build("borrower_idcard", "身份证"),
                KeyValue.build("litigation_number", "诉讼案号"),
                KeyValue.build("execution_number", "执行案号")
        ).collect(Collectors.toList()));
    }
}